package com.kun.oa.filter;

import com.kun.oa.entity.Account;
import com.kun.oa.entity.Permission;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Classname AccountFilter
 * @Created by FangKun
 * @Date 2023/1/3 0003 下午 20:08
 */
@Component
@WebFilter(urlPatterns = "/*")
public class AccountFilter implements Filter {

    //放行列表
    private final String[] IGNORE_URI = {"/index","/account/validataAccount","/css","/js","/account/login","/images","/errorPage"
                                        ,"/account/register","/account/logOut"};

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        String uri = request.getRequestURI();

        //先判断是否在放行列表
        boolean pass = canPass(uri);
        //在的话直接放行
        if(pass){
            filterChain.doFilter(request,response);
            return;
        }
        //不在的话，在session里边找account，看是否已经登录
        Account account = (Account) request.getSession().getAttribute("account");
        //没有登录就让登录页
        if(null == account){
            response.sendRedirect("/account/login");
            return;
        }

        /*if ("管理员".equals(account.getRole())){
            filterChain.doFilter(request,response);
        }*/

        // 已登录用户是否有权限访问当前页面
		if(!hasAuth(account.getPermissionList(),uri)) {

			request.setAttribute("msg", "哇喔，出错啦O(∩_∩)O~:" + uri);
			request.getRequestDispatcher("/errorPage").forward(request, response);
			return;
		}

        //登陆了就放行
        System.out.println("----------filter---------" + uri);
        filterChain.doFilter(request,response);
    }

    	private boolean hasAuth(List<Permission> permissionList, String uri) {
		// TODO Auto-generated method stub
		for (Permission permission : permissionList) {
			if(uri.startsWith(permission.getUri())) {
				return true;
			}
		}
		return false;
	}

    //判断，遍历放行列表，看URI是否以它开始
    private boolean canPass(String uri) {
        for (String val : IGNORE_URI){
            if(uri.startsWith(val))
                return true;
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("----------AccountFilter  init-----------------");

        Filter.super.init(filterConfig);
    }
}
